from django.shortcuts import render,redirect
from django.http import HttpResponse,request
from books.models import Book
from django.contrib.auth import authenticate,login

# Create your views here.
def hello(request):
    host = request.get_host()
    path = request.path
    html = "Current request host is %s\nCurrent request path is %s\n" % (host,path)
    return HttpResponse(html)

def display_meta(request):
    values = request.META.items()
    values
    html = []
    for k,v in values:
        tr = "<tr><td>%s</td><td>%s</td></tr>" % (k,v)
        html.append(tr)
    return HttpResponse("<table> %s </table>" % '\n'.join(html))


def search(request):
    error = False
    if 'q' in request.GET:
        q = request.GET['q']
        if not q:
            error = True
        else:
            books = Book.objects.filter(title__icontains = q)
            return render(request,'search_result.html',{'books':books,'query':q})
    else:
        return render(request,'search_form.html',{'error':error})

def my_view(request):
    if request.user.is_authenticated:
        return HttpResponse("你已经登录")
    if request.method == "POST":
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request,username=username,password=password)

        if user is not None:
            login(request,user)
            return redirect('/books')
        else:
            return render(request,'login.html')
    else:
        return render(request,'login.html')

